package com.situ.mall.web.interceptor;

import com.situ.mall.common.util.JWTUtil;
import com.situ.mall.common.util.StringUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

// token拦截器（只有需要验证token的走这里）
@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(response);

        // 从请求头中获取token
        String token = request.getHeader("token");

        // token为空，报错
        if (StringUtil.isBlank(token)) {
//            wrapper.sendRedirect("fail/token/null");
            System.out.println("null token");
            return false;
        }

        // 校验并解析token，解析错误就报错
        if (!JWTUtil.verifyToken(token)) {
//            wrapper.sendRedirect("fail/token/invalid");
            System.out.println("invalid token");
            return false;
        }

        System.out.println("valid token");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器处理结束...");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("请求结束...");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
